{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:06.344855Z",
     "start_time": "2018-09-06T01:49:03.629484Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import matplotlib as mpl \n",
    "%matplotlib inline\n",
    "from pandas.tseries.offsets import DateOffset\n",
    "import pickle\n",
    "import tensorflow as tf\n",
    "import random as rn\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(12345)\n",
    "tf.set_random_seed(1234)\n",
    "\n",
    "# 设置中文编码和负号的正常显示\n",
    "plt.rcParams['font.sans-serif'] = 'simhei'\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "Path = 'D:\\\\APViaML'\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:06.985066Z",
     "start_time": "2018-09-06T01:49:06.347362Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.049236Z",
     "start_time": "2018-09-06T01:49:06.987573Z"
    }
   },
   "outputs": [],
   "source": [
    "X_factor_microlist = pd.read_excel(Path + '\\\\data\\\\List.xlsx',sheet_name='Charac')\n",
    "X_factor_microlist = X_factor_microlist['Acronym']\n",
    "X_factor_macrolist = pd.read_excel(Path + '\\\\data\\\\List.xlsx',sheet_name='Macro')\n",
    "X_factor_macrolist = X_factor_macrolist['Acronym']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.054751Z",
     "start_time": "2018-09-06T01:49:07.051743Z"
    }
   },
   "outputs": [],
   "source": [
    "# # adjust X column order\n",
    "# col_list = np.array(top_1000_data_X.columns.values.tolist())\n",
    "# col_list[:94] = X_factor_microlist.values\n",
    "# top_1000_data_X = top_1000_data_X[col_list]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.062772Z",
     "start_time": "2018-09-06T01:49:07.056757Z"
    }
   },
   "outputs": [],
   "source": [
    "def creat_test_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "    return X_testdata, Y_testdata\n",
    "\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.071797Z",
     "start_time": "2018-09-06T01:49:07.064778Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_model_pre(model_name):\n",
    "    Y_pre_list_final= []\n",
    "    test_performance_score_list = []\n",
    "    for i in range(30):\n",
    "        X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "        model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "        file = open(model_filepath,'rb')\n",
    "        best_model = pickle.load(file)\n",
    "        file.close()        \n",
    "        Y_pre_list =best_model.predict(X_testdata)\n",
    "        test_score = Evaluation_fun(Y_pre_list, Y_testdata)\n",
    "        for x in Y_pre_list:\n",
    "            Y_pre_list_final.append(x)        \n",
    "        test_performance_score_list.append(test_score)\n",
    "    return Y_pre_list_final,test_performance_score_list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 这里解释一下变量的生成过程\n",
    "```\n",
    "*This is SAS code for generate Interaction variables\n",
    "*Interaction each characteristics with eight macro data;\n",
    "data data; set data;\n",
    "array base {*} &var_group2;\n",
    "array macro {*} b_m tbl ntis svar dp ep_macro tms dfy;\n",
    "array interaction {*} interaction_1-interaction_752;\n",
    "do i=1 to dim(base);\n",
    "do j=1 to dim(macro);\n",
    "n=(i-1)*8+j;\n",
    "interaction(n)=base(i)*macro(j);\n",
    "end;\n",
    "end;\n",
    "run;\n",
    "```\n",
    "* 微观变量的生成规则\n",
    "    * 1到8是代表特征1:absacc\n",
    "    * 9到18是代表特征2：acc\n",
    "    * 以此类推\n",
    "* 宏观变量的生成规则\n",
    "    * interation(n)中n/8余数，0代表b_m，1代表tbl\n",
    "    * 以此类推\n",
    "    \n",
    "因此计算Characteristic Importance总共分三步：\n",
    "1. 计算全变量下基准的R方，$R_r$\n",
    "2. 将第i个Characteristic替换成0，计算$R_i$，其中微观变量i=(1,2,...94)，宏观变量i=(1,2,...8)\n",
    "3. 第i个Characteristic的Importance由以下公式给出：\n",
    "\n",
    "\\begin{equation}\n",
    "VIP_i = (R_r-R_i)/\\sum_{i=1}^{94}(R_r-R_i)\n",
    "\\end{equation}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.079316Z",
     "start_time": "2018-09-06T01:49:07.074305Z"
    }
   },
   "outputs": [],
   "source": [
    "y_real = np.array(top_1000_data_Y.loc['1988':])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T01:49:07.085333Z",
     "start_time": "2018-09-06T01:49:07.081824Z"
    }
   },
   "outputs": [],
   "source": [
    "col_list = np.array(top_1000_data_X.columns.values.tolist())\n",
    "col_list = col_list[:94]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T03:16:43.726691Z",
     "start_time": "2018-09-06T01:49:07.091349Z"
    },
    "code_folding": [
     6,
     28
    ],
    "run_control": {
     "marked": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ENet\n",
      "RF\n",
      "GBRT\n"
     ]
    }
   ],
   "source": [
    "model_list1 = ['ENet','RF','GBRT']\n",
    "for x in model_list1:\n",
    "    model_name = str(x)\n",
    "    print(model_name)\n",
    "    score_loss_list = []\n",
    "    for j in range(len(X_factor_microlist)+1):   \n",
    "        if j == 0:\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "                file = open(model_filepath,'rb')\n",
    "                best_model = pickle.load(file)\n",
    "                file.close()        \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list \n",
    "            R_real = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "            \n",
    "        else:\n",
    "            j = j-1\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                num_list = list(range(j*8+94,(j+1)*8+94))\n",
    "                temp_char = X_factor_microlist[j]\n",
    "                for t in range(len(col_list)):\n",
    "                    if col_list[t] == temp_char:\n",
    "                        num1 = t\n",
    "                num_list.append(num1)\n",
    "                num_list.sort()\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                X_testdata[:,num_list] = 0\n",
    "\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'Model_'+model_name+'_Top1000_Prediction.pkl'\n",
    "                file = open(model_filepath,'rb')\n",
    "                best_model = pickle.load(file)\n",
    "                file.close()        \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list\n",
    "\n",
    "        new_score = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "        score_loss = new_score - R_real\n",
    "        score_loss_list.append(score_loss)\n",
    "\n",
    "    file = open(Path + '\\\\output\\\\data\\\\'+ model_name+'char_importance.pkl', 'wb')\n",
    "    pickle.dump(score_loss_list, file)\n",
    "    file.close()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-06T09:08:33.165250Z",
     "start_time": "2018-09-06T03:16:43.729698Z"
    },
    "code_folding": [
     6,
     13
    ]
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GBRT\n",
      "NN1\n",
      "NN2\n"
     ]
    }
   ],
   "source": [
    "from keras.models import load_model\n",
    "from keras import backend as K\n",
    "K.clear_session()\n",
    "tf.reset_default_graph()\n",
    "import gc\n",
    "model_list2 = ['NN1','NN2','NN3']\n",
    "for x in model_list2:\n",
    "    model_name = str(x)\n",
    "    print(model_name)\n",
    "    score_loss_list = []\n",
    "    for j in range(len(X_factor_microlist)+1):   \n",
    "        if j == 0:\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'_Model_'+model_name+'_Top1000_Prediction.h5'\n",
    "                best_model = load_model(model_filepath)   \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list[:,0]:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list \n",
    "                \n",
    "                K.clear_session()\n",
    "                tf.reset_default_graph()\n",
    "                gc.collect()\n",
    "                \n",
    "            R_real = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "            \n",
    "        else:\n",
    "            j = j-1\n",
    "            Y_pre_list_final= []\n",
    "            for i in range(30):\n",
    "                num_list = list(range(j*8+94,(j+1)*8+94))\n",
    "                temp_char = X_factor_microlist[j]\n",
    "                for t in range(len(col_list)):\n",
    "                    if col_list[t] == temp_char:\n",
    "                        num1 = t\n",
    "                num_list.append(num1)\n",
    "                num_list.sort()\n",
    "                X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "                X_testdata[:,num_list] = 0\n",
    "\n",
    "                model_filepath = Path + '\\\\model\\\\' + model_name+'\\\\'+ str(i+1988)+'_Model_'+model_name+'_Top1000_Prediction.h5'\n",
    "                best_model = load_model(model_filepath)\n",
    "                \n",
    "                Y_pre_list =best_model.predict(X_testdata)\n",
    "                temp_y_list = []\n",
    "                for x in Y_pre_list[:,0]:\n",
    "                    temp_y_list.append(x)\n",
    "                Y_pre_list_final =  Y_pre_list_final +  temp_y_list\n",
    "\n",
    "                K.clear_session()\n",
    "                tf.reset_default_graph()\n",
    "                gc.collect()\n",
    "                \n",
    "        new_score = Evaluation_fun(Y_pre_list_final,y_real)\n",
    "        score_loss = new_score - R_real\n",
    "        score_loss_list.append(score_loss)\n",
    "\n",
    "    file = open(Path + '\\\\output\\\\data\\\\'+ model_name+'char_importance.pkl', 'wb')\n",
    "    pickle.dump(score_loss_list, file)\n",
    "    file.close()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "390.2px",
    "left": "1047px",
    "right": "20px",
    "top": "120px",
    "width": "470.8px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
